import os
import requests
import json
import logging
from tqdm import tqdm
import urllib3  # 正确导入urllib3
import sys

# 配置日志
logging.basicConfig(
    filename='vivoApkUpload.log',
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
    encoding='utf-8'  # 指定编码为UTF-8
)
# 同时输出到控制台
console = logging.StreamHandler(sys.stdout)
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)

def get_apk_files(directory):
    """
    获取指定目录中的所有APK文件
    :param directory: 目录路径
    :return: APK文件路径列表
    """
    apk_files = []
    for file in os.listdir(directory):
        if file.lower().endswith('.apk'):
            apk_files.append(os.path.join(directory, file))
    return apk_files

def check_file_size(file_path, max_size_mb=500):
    """
    检查文件大小是否超过最大限制
    :param file_path: 文件路径
    :param max_size_mb: 最大文件大小(MB)
    :return: 是否符合大小要求
    """
    file_size_mb = os.path.getsize(file_path) / (1024 * 1024)  # 转换为MB
    return file_size_mb <= max_size_mb

def upload_apk(file_path, url, headers, params):
    """
    上传APK文件到指定接口
    :param file_path: APK文件路径
    :param url: 接口URL
    :param headers: 请求头
    :param params: 请求参数
    :return: 响应结果
    """
    try:
        # 准备文件
        files = {'file': (os.path.basename(file_path), open(file_path, 'rb'), 'application/vnd.android.package-archive')}
        
        # 发送POST请求
        response = requests.post(
            url=url,
            headers=headers,
            data=params,
            files=files,
            verify=False,  # 忽略SSL证书验证，注意在生产环境中应该启用证书验证
            timeout=300  # 设置超时时间为5分钟
        )
        
        # 关闭文件
        files['file'][1].close()
        
        # 返回响应结果
        return response
    except Exception as e:
        logging.error(f"上传过程中发生错误：{e}")
        return None

def main():
    # 指定APK文件所在目录
    apk_directory = "F:\\apk20250917\\fail"  # 请根据实际情况修改
    
    # 接口URL
    url = "https://192.168.202.242:8088/app/check/uploadApk"
    
    # 设置请求头
    headers = {
        'cookie': 'JSESSIONID=5754F68A624DE2CD9479B7D7DBDC8F26',
        'host': '192.168.202.242:8088',
        'origin': 'https://192.168.202.242:8088',
        'referer': 'https://192.168.202.242:8088/',
        'sec-fetch-mode': 'cors',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
        # 注意：不要在这里设置Content-Type，它会由requests自动设置为正确的multipart/form-data
    }
    
    # 设置请求参数
    params = {
        'check_base': 'true',
        'check_virus': 'false',
        'check_permit': 'false',
        'check_bug': 'false',
        'check_privacy': 'true',
        'check_service': 'false',
        'task_id': '358960359765454848'
    }
    
    # 禁用不安全请求的警告
    urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
    
    # 获取APK文件列表
    apk_files = get_apk_files(apk_directory)
    
    if not apk_files:
        logging.warning(f"在目录 {apk_directory} 中未找到APK文件")
        return
    
    logging.info(f"找到 {len(apk_files)} 个APK文件")
    
    # 遍历APK文件并上传
    for file_path in tqdm(apk_files, desc="处理APK文件"):
        file_name = os.path.basename(file_path)
        
        # 检查文件大小
        if not check_file_size(file_path):
            logging.warning(f"[跳过] {file_name} - 文件大小超过500MB限制")
            continue
        
        logging.info(f"正在上传: {file_name}")
        
        # 上传文件
        response = upload_apk(file_path, url, headers, params)
        
        # 处理响应
        if response and response.status_code == 200:
            try:
                result = response.json()
                logging.info(f"上传成功: {file_name}")
                logging.debug(f"响应结果: {json.dumps(result, ensure_ascii=False, indent=2)}")
            except:
                logging.warning(f"上传成功，但无法解析响应: {response.text[:100]}...")
        else:
            status_code = response.status_code if response else "请求失败"
            logging.error(f"上传失败: {file_name}, 状态码: {status_code}")
            if response:
                logging.error(f"错误信息: {response.text[:200]}...")

if __name__ == "__main__":
    main()

